//
//  PhotoCell.m
//  WXMovie
//
//  Created by apple on 16/4/6.
//  Copyright © 2016年 无限互联. All rights reserved.
//

#import "PhotoCell.h"

@implementation PhotoCell
{
    UIImageView *imageView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self _createImageView];
    }
    
    return self;
}

- (void)awakeFromNib {

    [super awakeFromNib];
    [self _createImageView];
}

- (void)setImgUrlStr:(NSString *)imgUrlStr
{
    _imgUrlStr = imgUrlStr;
    
   [imageView sd_setImageWithURL:[NSURL URLWithString:_imgUrlStr]];
    
    
    
}

- (void)_createImageView
{
    
    
    imageView = [[UIImageView alloc] initWithFrame:self.bounds];
    
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    imageView.center = CGPointMake(kScreenWidth / 2, kScreenHeight /2 - 50);
    
    imageView.userInteractionEnabled = YES;
    [imageView addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(savePhoto:)]];
    
    [self.contentView addSubview:imageView];
}

- (void)savePhoto:(UILongPressGestureRecognizer *)longPress {
    
 
        UIImage *photo = imageView.image;

        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否保存图片" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            if (photo) {
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window animated:YES];
                hud.labelText = @"Waiting";
                hud.dimBackground = YES;
                UIImageWriteToSavedPhotosAlbum(photo, self, @selector(image: didFinishSavingWithError: contextInfo:), (__bridge void * _Nullable)(hud));
                
            }
        }];
        [alertView addAction:cancleAction];
        [alertView addAction:sureAction];
        UIResponder *next = self.nextResponder;
        
        while (1) {
            if ([next isKindOfClass:[UIViewController class]]) {
//                 NSLog(@"%@",next);
                break;
            } else {
//                NSLog(@"%@",next);
                next = next.nextResponder;
              
            }
        }
        
        [(UIViewController *)next presentViewController:alertView animated:YES completion:nil];
        
    
    
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    MBProgressHUD *hud = (__bridge MBProgressHUD *)(contextInfo);
    
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark"]];
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = @"Success";
    [hud hide:YES afterDelay:1.5];
//    NSLog(@"保存成功");
}

@end
